<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addFeeRules">增加停车计费规则</el-button>
      <el-button @click="exportExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" :index="indexMethod" width="50" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="scope">
            {{ formateType(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="editCarRule(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteCarRule(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页和eltable是相互独立的 -->
      <!-- 必须的配置项：total pagesize 总页数= 总页数/总容量 -->
      <div class="pager" style="margin-top: 20px">
        <el-pagination
          class="page-container"
          :total="total"
          :page-size="params.pageSize"
          layout="prev, pager, next"
          @current-change="editPageList"
        />
      </div>
    </div>
    <!-- 弹框 -->
    <addRules
      ref="addRules"
      :dialog-visible.sync="dialogVisible"
      @GetRuleList="getRuleList"
    />
    <!-- 添加计费规则弹框 -->
  </div>
</template>

<script>
import { getRuleListAPI, deleteRuleListAPI } from '@/api/carRule'
import { utils, writeFileXLSX } from 'xlsx'
import addRules from './components/addRules.vue'
export default {
  name: 'Building',
  components: {
    addRules
  },
  data() {
    return {
      ruleList: [],
      params: {
        page: 1,
        pageSize: 5
      },
      total: 0,
      dialogVisible: false
      // editId: 0

    }
  },
  computed: {

  },
  // 切换计费规则，清空校验结果，两种方法，
  // 1，根据elmentui自带的change属性，设置事件
  // 2.添加watch事件，进行监听，监听chargeType的值是否发生改变，改变就清空表单校验结果

  created() {
    this.getRuleList()
  },
  methods: {
    // 获取计费列表
    async getRuleList() {
      const res = await getRuleListAPI(this.params)
      // console.log(res)
      this.ruleList = res.data.rows
      this.total = res.data.total
    },
    // 切换页面
    editPageList(currentPage) {
      this.params.page = currentPage
      this.getRuleList()
    },
    // 页面编号显示
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 将页面数据以excel的格式导出到本地
    // 注意: 此处只模拟导出Excel功能, 实际开发中, 需要使用js-xlsx相关API进行实现
    async exportExcel() {
      const res = await getRuleListAPI(this.params)
      // 要求导出的字段名
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      const tableHeader = res.data.rows.map(item => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 要导出的表头中文字段
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表 要求一个对象数组格式
      const worksheet = utils.json_to_sheet(tableHeader)
      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头（将表头数据改写）
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, 'test.xlsx')
    },
    // 计费方式的格式化方法
    formateType(type) {
      const Map = {
        duration: '时长计费',
        turn: '按次收费',
        partition: '分段计费'
      }
      return Map[type]
    },
    // 添加计费规则
    addFeeRules() {
      this.dialogVisible = true
      // this.editid = 0
    },
    // 编辑企业信息I
    async editCarRule(id) {
      this.dialogVisible = true
      // this.editId = id
      this.$refs.addRules.showRuleList(id)
      // console.log(this.editId)
      // this.$router.push({
      //   name: 'AddRules',
      //   params: {
      //     id: id
      //   }})
    },
    // 删除计费规则
    async deleteCarRule(id) {
      this.$confirm('此操作将删除该计费规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRuleListAPI(id)
        this.getRuleList()
        this.$message.success('删除成功')
        // 判断是否当页最后一条，是的话，page--
        if (this.ruleList.length === 1 && this.params.page > 1) {
          this.params.page--
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}

</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
